import hashlib
import random
import string
import time

class SignatureVerifier:
    """签名验证功能"""
    
    def __init__(self, token):
        """
        初始化签名验证器
        
        Args:
            token: 企业微信的Token
        """
        self.token = token

    def get_signature(self, timestamp, nonce, msg_encrypt):
        """
        生成签名 - 按照企业微信官方文档
        
        Args:
            timestamp: 时间戳
            nonce: 随机字符串
            msg_encrypt: 加密的消息
            
        Returns:
            SHA1签名字符串
        """
        # 按照字典序排序：token、timestamp、nonce、msg_encrypt
        sortlist = [self.token, timestamp, nonce, msg_encrypt]
        sortlist.sort()
        # 拼接字符串
        sort_str = ''.join(sortlist)
        # SHA1计算
        sha = hashlib.sha1()
        sha.update(sort_str.encode('utf-8'))
        return sha.hexdigest()

    def verify_signature(self, msg_signature, timestamp, nonce, msg_encrypt):
        """
        验证签名
        
        Args:
            msg_signature: 消息签名
            timestamp: 时间戳
            nonce: 随机字符串
            msg_encrypt: 加密的消息
            
        Returns:
            bool: 签名是否有效
        """
        signature = self.get_signature(timestamp, nonce, msg_encrypt)
        return signature == msg_signature

    def generate_nonce(self, length=16):
        """
        生成随机字符串
        
        Args:
            length: 字符串长度
            
        Returns:
            随机字符串
        """
        return ''.join(random.sample(string.ascii_letters + string.digits, length))

    def get_current_timestamp(self):
        """
        获取当前时间戳
        
        Returns:
            当前时间戳字符串
        """
        return str(int(time.time())) 